package znet

import (
	"fmt"
	"net"
	"zinx-tianjing-study/util"
	"zinx-tianjing-study/ziface"
)

// IServer接口实现，定义一个服务器模块
type Server struct {
	Name              string
	IPVersion         string
	IP                string
	Port              int
	MessageHandle     ziface.IMessageHandle
	ConnectionManager ziface.IConnectionManage

	OnConnStart func(ziface.IConnection)
	OnConnStop  func(ziface.IConnection)
}

func (s *Server) Start() {
	fmt.Printf("[Start] 服务器监听%s:%d\n", s.IP, s.Port)

	go func() {
		addr, err := net.ResolveTCPAddr(s.IPVersion, fmt.Sprintf("%s:%d", s.IP, s.Port))
		if err != nil {
			fmt.Println("解析地址失败:", err)
			return
		}

		listener, err := net.ListenTCP(s.IPVersion, addr)
		if err != nil {
			fmt.Println("监听失败:", err)
			return
		}
		defer listener.Close()

		fmt.Printf("[Running] 开始处理客户端连接\n")
		cid := 0

		for {
			conn, err := listener.AcceptTCP()
			if err != nil {
				fmt.Println("Accept err:", err)
				continue
			}

			// 使用全局配置的最大连接数
			if s.ConnectionManager.Len() >= util.GlobalObject.MaxConn {
				fmt.Printf("连接数已达到上限 %d，拒绝新连接\n", util.GlobalObject.MaxConn)
				conn.Close()
				continue
			}

			zconn := NewConnection(s, conn, uint32(cid), s.MessageHandle)
			s.ConnectionManager.Add(zconn)
			cid++

			// 启动连接
			go zconn.Start()
		}
	}()
}

func (s *Server) Stop() {
	fmt.Println("[Stop] 正在停止服务器，清理所有连接...")
	s.ConnectionManager.ClearConn()
}

func (s *Server) Serve() {
	s.Start()

	// 阻塞主协程
	select {}
}

func (s *Server) AddRouter(msgID uint32, router ziface.IRouter) {
	s.MessageHandle.AddRouter(msgID, router)
	fmt.Printf("[AddRouter] 消息ID: %d 的路由已注册\n", msgID)
}

func (s *Server) GetConnManger() ziface.IConnectionManage {
	return s.ConnectionManager
}

// 设置连接建立前的Hook
func (s *Server) SetOnConnStart(startFunc func(ziface.IConnection)) {
	s.OnConnStart = startFunc
}

// 设置连接断开前的Hook
func (s *Server) SetOnConnStop(stopFunc func(ziface.IConnection)) {
	s.OnConnStop = stopFunc
}

// 调用连接建立Hook
func (s *Server) CallOnConnStart(conn ziface.IConnection) {
	if s.OnConnStart != nil {
		fmt.Println("[Hook] 正在执行 OnConnStart()")
		s.OnConnStart(conn)
	}
}

// 调用连接断开Hook
func (s *Server) CallOnConnStop(conn ziface.IConnection) {
	if s.OnConnStop != nil {
		fmt.Println("[Hook] 正在执行 OnConnStop()")
		s.OnConnStop(conn)
	}
}

func NewServer(name string) ziface.IServer {
	s := &Server{
		Name:      util.GlobalObject.Name,
		IPVersion: "tcp4",
		IP:        util.GlobalObject.Host,
		Port:      util.GlobalObject.TcpPort,
		MessageHandle: NewMessageHandle(&MessageHandleConfig{
			WorkerPoolSize: util.GlobalObject.WorkerPoolSize,
			TaskQueueSize:  util.GlobalObject.TaskQueueSize,
			DebugMode:      util.GlobalObject.LogConfig.LogLevel == "debug",
		}),
		ConnectionManager: NewConnectionManager(),
	}

	// 保存服务器句柄
	util.GlobalObject.TcpServer = s
	return s
}
